
import axios from 'axios'
import {baseUrl} from './env';
import { router } from './router'
import Vue from 'vue'
import { Dialog,Toast  } from 'vant'
// 全局注册
Vue.use(Dialog);
Vue.use(Toast);

const service =axios.create({
  baseURL: baseUrl, // 后台服务地址
  timeout: 10000, // 请求超时时间
});
/*设置拦截器 */  
  service.interceptors.request.use(
    config => {
      //  可在此处配置请求头信息
        var token = localStorage.getItem("token")
        if (token!=null&&token!=undefined) {
          // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
          config.headers['Authorization'] = token
        }
      if (config.method == "post") {
          // config.data = qs.stringify(config.data)
      }

      return config
    },
    error => {
      Promise.reject(error)
    }
  )
  //发送请求
  service.interceptors.response.use(
    response => {
      const res = response.data;
      if (res.retCode != 200) {
        if (res.retCode == 510) {
          Dialog.alert({
            title: '提示',
            message: '你已被登出，请重新登录',
            showCancelButton:true,
          }).then(() => {
            localStorage.removeItem("token")
            router.push({path: '/login'})
          });
          return;
        }
        return response.data;
      } else {
        return response.data;
      }
    },
    error => {     
      return Promise.reject(error)
    }
  )

  export default service
  // export default servicef